<template>
  <el-dialog
      v-model="dialogVisible"
      title="经费外拨新增"
      :close-on-click-modal="false"
      width="80%"
  >
    <div v-loading="loading">
      <div>
        <div class="title-col">基本信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">
            <el-select @change="changeselect"
                       @focus="getselectVproject"
                       v-model="projectInfo.projectId"
                       @input="handleInput"
                       filterable
                       placeholder="请选择项目名称">
              <el-option
                  v-for="(item, index) in projectOptions"
                  :key="item.projectId"
                  :label="item.name"
                  :value="item.projectId"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            {{ projectInfo.chargerName }}
          </el-descriptions-item>
          <el-descriptions-item label="外拨总金额">
            {{ turnWanyuan(projectInfo.outFee) }}
          </el-descriptions-item>
          <el-descriptions-item label="已拨经费">
            {{ turnWanyuan(projectInfo.isOutFee) }}
          </el-descriptions-item>
          <el-descriptions-item label="可外拨金额">
            {{ turnWanyuan(projectInfo.notOutFee )}}
          </el-descriptions-item>
          <el-descriptions-item label="外拨待审核金额">
            {{ turnWanyuan(projectInfo.outFeeIncheck) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请外拨日期">
            <el-date-picker
                v-model="projectInfo.outbounddate"
                type="date"
                placeholder="选择申请外拨日期"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="title-col">外拨信息</div>
        <el-table :data="projectInfo.projectOutboundList" border>
          <el-table-column label="序号" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="合作单位名称"></el-table-column>
          <el-table-column prop="chargerName" label="负责人"></el-table-column>
          <el-table-column prop="status" label="已外拨/未外拨(万元)">
            <template #default="scope">
             {{ turnWanyuan(scope.row.isOutFee)}}/{{turnWanyuan(scope.row.notOutFee)}}
            </template>
          </el-table-column>
          <el-table-column label="外拨经费(万元)">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.outboundFee"
                  :min="0"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="银行名称">
            <template #default="scope">
              <el-input v-model="scope.row.bankName" placeholder="请输入银行名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="银行账号">
            <template #default="scope">
              <el-input v-model="scope.row.bankNum" placeholder="请输入银行账号"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSave">暂存</el-button>
<!--        <el-button @click="submit">提交</el-button>-->
        <el-button type="primary" @click="handleSaveAndPass">保存并通过</el-button>
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup >
import { ref, defineProps, defineEmits } from "vue";
import {convertOutboundFeeToYuan, turnWanyuan, turnyuan} from './../../../utils/money.js'
import {
  selectVproject,
  getProOutFeeInfo,
  add
} from '@/api/money/jfwbApi.js'
import {ElMessage} from "element-plus";
const loading = ref(false) // 添加加载状态
const getselectVproject = function (){
  selectVproject({
    pageNum:1,
    pageSize:50,
    projectClass:"zXProject",
    type:"outbound",
  })

      .then((res)=>{
        console.log(projectInfo.value)
        projectOptions.value = res.rows
      })
}
const changeselect =function (){
  console.log(projectInfo.value)
  getProOutFeeInfo({projectId:projectInfo.value.projectId})
      .then((res)=>{
        projectInfo.value = res.data
      })
}

// 接收父组件传递的 props
const props = defineProps({
  // projectOptions: {
  //   type: Array,
  //   default: () => []
  // },
  // projectInfo: {
  //   type: Object,
  //   default: () => ({})
  // },
  tableData: {
    type: Array,
    default: () => []
  }
});

// 模拟表格数据
const tableData = ref([]);

// 模拟项目信息数据
const projectInfo = ref(
    {
      status:'-1',//保存传-1，保存并通过传2"
      //checkstatus:'-1',//保存传-1，保存并通过传2"
  projectId: '',
  outFee: '',//外拨总金额
  availableAllocatedAmount: '',
  outbounddate: new Date(),
  chargerName: '', //负责人名称
  isOutFee: '',//已拨经费
  outFeeIncheck: '',//外拨待审核金额
  notOutFee:'',//可外拨金额
  projectOutboundList:[
      {
        index: '',
        unitName: '',//合作单位名称
        chargerName: '',//负责人
        isOutFee: '', //已外拨(万元)
        notOutFee: '',//未外拨
        outboundFee: 0,//外拨经费(万元)
        bankName: '',//银行名
        bankNum: ''//卡号
  }],
}
);
const dialogVisible = ref(false);



// 定义项目名称下拉框选项，使用父组件传递的数据
// const projectOptions = ref(props.projectOptions);
const projectOptions = ref([]);
// 定义事件，用于通知父组件保存操作
const emits = defineEmits(['getlists','save', 'saveAndPass', 'close','getselectVproject']);
const x = () => {
  emits('getlist');
}

// 检查外拨经费是否不大于未外拨经费，并记录不符合项的合作单位名称
const checkOutboundFee = () => {
  const invalidUnitNames = [];
  for (const item of projectInfo.value.projectOutboundList) {
    const outboundFeeInYuan = (parseFloat(item.outboundFee) || 0) * 10000;
    const notOutFee = parseFloat(item.notOutFee) || 0;
    if (outboundFeeInYuan > notOutFee) {
      invalidUnitNames.push(item.unitName);
    }
  }
  if (invalidUnitNames.length > 0) {
    ElMessage({
      type: 'error',
      message: `存在外拨经费大于未外拨经费的情况，涉及合作单位：${invalidUnitNames.join(', ')}，请重新输入！`
    });
    return false;
  }
  return true;
};
// 提交按钮点击事件处理函数
const submit = () => {
  if (!checkOutboundFee()) {
    return;
  }
  projectInfo.value.status = '1'
  add(convertOutboundFeeToYuan(projectInfo.value))
      .then((res)=>{
        if(res.code ==200){
          ElMessage({
            type: 'success',
            message: res.msg,
          })
          dialogVisible.value = false;
          emits('getlist');
        }else {
          ElMessage({
            type: 'info',
            message: res.msg,
          })
        }
      })
  // console.log('保存操作', convertOutboundFeeToYuan(projectInfo.value));
  //
  // console.log('保存操作', projectInfo.value);
  // emits('save', projectInfo.value);
  // dialogVisible.value = false;
};
// 保存按钮点击事件处理函数
const handleSave = () => {
  if (!checkOutboundFee()) {
    return;
  }
  projectInfo.value.status = '-1'
  loading.value = true
  add(convertOutboundFeeToYuan(projectInfo.value))
      .then((res)=>{
        if(res.code ==200){
          ElMessage({
            type: 'success',
            message: res.msg,
          })
          dialogVisible.value = false;
          emits('getlist');
        }else {
          ElMessage({
            type: 'info',
            message: res.msg,
          })
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
  // console.log('保存操作', convertOutboundFeeToYuan(projectInfo.value));
  //
  // console.log('保存操作', projectInfo.value);
  // emits('save', projectInfo.value);
  // dialogVisible.value = false;
};

// 保存并通过按钮点击事件处理函数

const handleSaveAndPass = () => {
  if (!checkOutboundFee()) {
    return;
  }
  projectInfo.value.status = '2'
  loading.value = true
  add(convertOutboundFeeToYuan(projectInfo.value))
      .then((res)=>{
        if(res.code ==200){
          ElMessage({
            type: 'success',
            message: res.msg,
          })
          dialogVisible.value = false;
          emits('getlist');
        }else {
          ElMessage({
            type: 'info',
            message: res.msg,
          })
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
  // console.log('保存并通过操作',convertOutboundFeeToYuan(projectInfo.value));
  // emits('saveAndPass', projectInfo.value);
  // dialogVisible.value = false;
};
// 清空所有信息的方法
const clearAllInfo = () => {
  // 重置 projectInfo
  projectInfo.value = {
    status: '-1',
    projectId: '',
    outFee: '',
    availableAllocatedAmount: '',
    outbounddate: new Date(),
    chargerName: '',
    isOutFee: '',
    outFeeIncheck: '',
    notOutFee: '',
    projectOutboundList: [
      {
        index: '',
        unitName: '',
        chargerName: '',
        isOutFee: '',
        notOutFee: '',
        outboundFee: 0,
        bankName: '',
        bankNum: ''
      }
    ]
  };
  // 重置 tableData
  tableData.value = [];
};

// 定义一个方法用于打开弹窗
const openDialog = () => {
  clearAllInfo(); // 在打开弹窗时调用清空方法
  dialogVisible.value = true;

};
// 搜索方法
// 处理输入值的函数
const handleInput = (inputValue) => {
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    // name:'项目新增'
    name:inputValue.data
  })
      .then((res) => {
        projectOptions.value = res.rows
      })
  //console.log('用户输入的值:', inputValue);
  // 在这里可以添加根据输入值调用其他函数的逻辑
  // 例如，根据输入值进行搜索、过滤等操作
};

// 暴露 openDialog 方法供父组件调用
defineExpose({
  openDialog
});

</script>

<style scoped lang="scss">
.title-col {
  color: #337AB7;
  font-weight: bolder;
  margin: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>